package com.android.JiYclock.expand;

import com.android.JiYclock.AlarmClock;
import com.android.JiYclock.Alarms;
import com.android.JiYclock.Log;
import com.android.JiYclock.R;
import com.android.jiYsoundrecorder.Recorder;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.res.AssetFileDescriptor;
import android.content.res.Resources;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnErrorListener;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Vibrator;
import android.view.View;
import android.widget.Button;
import android.widget.Chronometer;
import android.widget.ProgressBar;
import android.widget.TextView;

public class VoiceInfoPlay extends Activity {
	

	private static final long[] sVibratePattern = new long[] { 500, 500 };
    private boolean mPlaying = false;
    private MediaPlayer mMediaPlayer;
    private ProgressBar mProgress;
    private Button endPlayButton;
    private Chronometer beginTime;
    private TextView endTime;
    private String mTimerFormat;
    int mSampleLength = 0;
    long mSampleStart = 0;
    
    public int getmSampleLength() {
		return mSampleLength;
	}

	private Handler  mHandler = new Handler();
    private Runnable  mUpdateTimer = new Runnable() {
     public void run() { 
     	updateTimerView(mMediaPlayer); 
     }
 };

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.alarm_alert_play);
        mTimerFormat = getResources().getString(R.string.timer_format);
		init(); 
		Intent intent =getIntent();
		Bundle bundle = intent.getExtras();
		String location = bundle.getString("location");
		play(location);
		updateTimerView(mMediaPlayer);
		endPlayButton.setOnClickListener(new Button.OnClickListener() {
			
			@Override
			public void onClick(View v) {
	            stop();
	            Intent intent = new Intent(VoiceInfoPlay.this,AlarmClock.class);
	            startActivity(intent);
			}
		});
	}
	
	private void init(){
		
		mProgress = (ProgressBar)findViewById(R.id.progressbar); 
		mProgress.setVisibility(View.VISIBLE);
		endPlayButton = (Button)findViewById(R.id.endplay);
		beginTime = (Chronometer)findViewById(R.id.beginTime);
		endTime = (TextView)findViewById(R.id.endTime);
		
	}
	
	
	
	 private void updateTimerView(MediaPlayer mMediaPlayer) {
	       
		 
		    beginTime.start();
		    long time =beginTime.getDrawingTime();
		    long temp = mMediaPlayer.getDuration();
		    Log.v("sdsdsdsdsdsds"+String.valueOf(temp));
		    if(time ==mMediaPlayer.getDuration())
		    {
		    	beginTime.stop();
		    }
	        String times=String.format(mTimerFormat, temp/60, temp%60);
	        String timeStr = String.format(mTimerFormat, time/60, time%60);
	        beginTime.setText(timeStr);
	        endTime.setText(times);
	        
	        mProgress.setProgress((int)(100*time/time));
	        mHandler.postDelayed(mUpdateTimer, 1000);
	    }
	
	
/**
 * 音频播放信息
 */
    private void play(String location) {
        // stop() checks to see if we are already playing.
        stop();
        mSampleStart = System.currentTimeMillis();
          
            mMediaPlayer = new MediaPlayer();
            mMediaPlayer.setOnErrorListener(new OnErrorListener() {
                public boolean onError(MediaPlayer mp, int what, int extra) {
                    Log.e("Error occurred while playing audio.");
                    mp.stop();
                    mp.release();
                    mMediaPlayer = null;
                    return true;
                }
            });
            try {
                	Uri sourceuri = Uri.parse(location);
                    mMediaPlayer.setDataSource(this,sourceuri);
                    startPlay(mMediaPlayer);
            } catch (Exception ex) {
                Log.v("Using the fallback ringtone");
                // The alert may be on the sd card which could be busy right
                // now. Use the fallback ringtone.
                try {
                    // Must reset the media player to clear the error state.
                    mMediaPlayer.reset();
                    setDataSourceFromResource(getResources(), mMediaPlayer,
                            R.raw.fallbackring);
                    
 
                    startPlay(mMediaPlayer);
                } catch (Exception ex2) {
                    // At this point we just don't play anything.
                    Log.e("Failed to play fallback ringtone", ex2);
                }
            }
        mPlaying = true;
    }

    // Do the common stuff when starting the alarm.
    private void startPlay(MediaPlayer player)
            throws java.io.IOException, IllegalArgumentException,
                   IllegalStateException {
        final AudioManager audioManager = (AudioManager)getSystemService(Context.AUDIO_SERVICE);
        // do not play alarms if stream volume is 0
        //如果此时音量为0，那就不播放闹铃
        if (audioManager.getStreamVolume(AudioManager.STREAM_ALARM) != 0) {
            player.setAudioStreamType(AudioManager.STREAM_ALARM);
            player.setLooping(true);
            player.prepare();
            player.start();
        }
    }

    private void setDataSourceFromResource(Resources resources,
            MediaPlayer player, int res) throws java.io.IOException {
        AssetFileDescriptor afd = resources.openRawResourceFd(res);
        if (afd != null) {
            player.setDataSource(afd.getFileDescriptor(), afd.getStartOffset(),
                    afd.getLength());
            afd.close();
        }
    }

    /**
     * Stops alarm audio and disables alarm if it not snoozed and not
     * repeating
     */
    public void stop() {
      Log.v("AlarmKlaxon.stop()");
        if (mPlaying) {
            mPlaying = false;

            Intent alarmDone = new Intent(Alarms.ALARM_DONE_ACTION);
            sendBroadcast(alarmDone);

            // Stop audio playing
            if (mMediaPlayer != null) {
                mMediaPlayer.stop();
                mMediaPlayer.release();
      
                mMediaPlayer = null;
            }
        }
    }
    
    public void start(){
    	mMediaPlayer.start();
    }
    
    public void pause(){
    	mMediaPlayer.pause();
    }
}
